#!/usr/bin/env python
"""
AUTH interface for Addama

Provides HTTP authorization via addama-login. Optionally generates a file
containing login cookie information.

For more information, please see the documentation in README.txt, or simply
issue help() on any function or module contained within this package.

For license information, please see LICENSE.txt.


Author: Tom Robinson <trobinson@systemsbiology.org>
Initial Revision: April 14th, 2010

"""

# Imports

import cookielib
import sys
from urlparse import urlparse,urljoin

import addama.api
from config import *


# Function main
#  This is non-standard, and should not be confused with __main__, 
#  which indicates this script is called directly.
def _fmain():
    """Function main: analog for the \"main\" function in other languages""" 
    url = None
    username = None
    password = None
    if len(sys.argv) > 1:
        url = sys.argv[1]
    if len(sys.argv) > 2:
        username = sys.argv[2]
    if len(sys.argv) > 3:
        password = sys.argv[3]

    given = urlparse(url)    
    authCookies = cookielib.CookieJar()

    # Scheme (eg. HTTP, HTTPS) and host location must be given
    if given.scheme == '' or given.netloc == '':
        raise ValueError
    
    # Check if we need to add ADDAMA_LOGIN information and get our cookies 
    if given.path == '' and ADDAMA_LOGIN:
        authCookies = \
            addama.api.auth.interactiveLogin(urljoin(url,ADDAMA_LOGIN), \
            username, password)
    else:
        authCookies = \
            addama.api.auth.interactiveLogin(url, \
            username, password)

    addama.api.auth.saveCookies(AUTH_COOKIES,authCookies)


# Initialization and Execution
# Direct invocation
if __name__ == "__main__":
    _fmain()

# Library invocation
# If included as part of a package, the caller is responsible for
# initialization and executing _fmain()
